package com.hmall.search.listen;

import com.alibaba.fastjson.JSON;
import com.hmall.common.feigin.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.search.constant.EsConstant;
import com.hmall.common.config.MqConstant;
import com.hmall.search.pojo.ItemDto;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 监听类
 *
 * @Author Json.D
 * @Date 2022/8/11 19:42
 * @Blog
 * @Description: 监听类
 */
@Component
public class listener {

    @Autowired
    RestHighLevelClient client;

    @Autowired
    ItemClient itemClient;


    @RabbitListener(bindings =@QueueBinding(
            value = @Queue(name = MqConstant.ITEM_INSERT_QUEUE),
            exchange = @Exchange(value = MqConstant.EXCHANGE_DIRECT,type = ExchangeTypes.DIRECT),
            key = MqConstant.BINDINGKEY_ITEM_INSERT
    ))
    public void  listenWithInsert(String id) throws IOException {
        Item item = itemClient.getById(Long.valueOf(id));
        IndexRequest indexRequest=new IndexRequest(EsConstant.INDEX).id(id);
        ItemDto itemDto = new ItemDto(item);
        String json = JSON.toJSONString(itemDto);
        indexRequest.source(json, XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);
    };

    @RabbitListener(bindings =@QueueBinding(
            value = @Queue(name = MqConstant.ITEM_DELETE_QUEUE),
            exchange = @Exchange(value = MqConstant.EXCHANGE_DIRECT,type = ExchangeTypes.DIRECT),
            key = MqConstant.BINDINGKEY_ITEM_DELETE
    ))
    public void  listenWithDelete(String id) throws IOException {

        DeleteRequest deleteRequest=new DeleteRequest(EsConstant.INDEX).id(id);
        client.delete(deleteRequest, RequestOptions.DEFAULT);
    }
}
